package com.bsoft.gol.hbs.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p> Bean工具类 </p>
 * User: chendw
 * Date: 2017/4/27 10:07
 */
public class BeanUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 属性拷贝
     *
     * @param source      源对象
     * @param targetClass 目标对象类
     * @param <T>         目标对象实体类
     * @return 实体对象，异常返回null
     */
    public static <T> T copyProperties(Object source, Class<T> targetClass) {
        try {
            T target = targetClass.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, target);
            return target;
        } catch (InstantiationException | IllegalAccessException | BeansException e) {
            LOGGER.error("拷贝属性异常", e);
        }
        return null;
    }

    /**
     * 集合拷贝
     *
     * @param list  集合对象
     * @param clazz 目标集合类
     * @param <T>   目标集合实体对象
     * @return
     */
    public static <T> List<T> copyList(List<?> list, Class<T> clazz) {
        if (list == null) {
            return null;
        } else {
            ArrayList result = new ArrayList();
            Iterator i$ = list.iterator();

            while (i$.hasNext()) {
                Object object = i$.next();
                result.add(copyProperties(object, clazz));
            }

            return result;
        }
    }


}
